package com.education.platform.common.encrypt;



import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * MD5工具
 */
public class MD5Util {

    private static final Logger LOGGER = LoggerFactory.getLogger(MD5Util.class);

    /**
     * 32位加密,需要加密的明文
     */
    public static final String encrypt(String plainText, String salt) {
        String s;
        if (StringUtils.isNotEmpty(salt)) {
            s = String.format("%s=%s", plainText, salt);
        } else {
            s = plainText;
        }
        return encrypt(s, true);
    }


    /**
     * 可设置加密位数 的 加密（可选位数：16，32）
     */
    private static final String encrypt(String plainText, Boolean isFull) {
        String resultStr = "";
        MessageDigest md ;
        byte rSArr[];
        int theBitNum;
        StringBuffer md5Str = new StringBuffer("");

        try {
            md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes("utf-8"));
            rSArr = md.digest();
            for (int offset = 0; offset < rSArr.length; offset++) {
                theBitNum = rSArr[offset];
                if (theBitNum < 0) {
                    theBitNum += 256;
                }
                if (theBitNum < 16) {
                    md5Str.append("0");
                }
                md5Str.append(Integer.toHexString(theBitNum));
            }
            resultStr = isFull ? md5Str.toString() : md5Str
                    .toString().substring(8, 24);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return resultStr;
    }



}
